﻿using System.Security.Cryptography;

namespace Devonline.Security;

/// <summary>
/// RSA 算法提供加解密的数据安全服务
/// </summary>
public class RSASecurityService(SecuritySetting securitySetting) : AsymmetricSecurityService(securitySetting), IAsymmetricSecurityService, ISecurityService
{
    /// <summary>
    /// 使用公钥加密数据
    /// </summary>
    /// <param name="publicKey">加密用的公钥</param>
    /// <param name="data">待加密的数据</param>
    /// <returns>加密后的数据</returns>
    public override byte[] Encrypt(byte[] publicKey, byte[] data)
    {
        using var rsa = RSA.Create();
        rsa.ImportRSAPublicKey(publicKey, out int readLength);
        if (readLength != publicKey.Length)
        {
            throw new ArgumentNullException($"RSA security service public key length: {publicKey.Length} not equal imported length: {readLength}!");
        }

        return rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
    }
    /// <summary>
    /// 使用私钥解密数据
    /// </summary>
    /// <param name="privateKey">解密用的私钥</param>
    /// <param name="data">待解密的数据</param>
    /// <returns>解密后的数据</returns>
    public override byte[] Decrypt(byte[] privateKey, byte[] data)
    {
        using var rsa = RSA.Create();
        rsa.ImportRSAPrivateKey(privateKey, out int readLength);
        if (readLength != privateKey.Length)
        {
            throw new ArgumentNullException($"RSA security service private key length: {privateKey.Length} not equal imported length: {readLength}!");
        }

        return rsa.Decrypt(data, RSAEncryptionPadding.Pkcs1);
    }

    public override Task<byte[]> EncryptAsync(byte[] data)
    {
        throw new NotImplementedException();
    }
    public override Task<byte[]> DecryptAsync(byte[] data)
    {
        throw new NotImplementedException();
    }

    public override void Generate(out byte[] privateKey, out byte[] publicKey)
    {
        throw new NotImplementedException();
    }
    public override Task GenerateAsync(string keyName, KeyGenerateMode generateMode = KeyGenerateMode.Both)
    {
        throw new NotImplementedException();
    }

    public override Task ImportAsync(string fileName)
    {
        throw new NotImplementedException();
    }
    public override void Import(byte[] publicKey, byte[]? privateKey = null)
    {
        throw new NotImplementedException();
    }
}